package com.hjrpc.babyyamall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjrpc.babyyamall.product.dao.AttrDao;
import com.hjrpc.babyyamall.product.dao.SpuInfoDao;
import com.hjrpc.babyyamall.product.dao.SpuInfoDescDao;
import com.hjrpc.babyyamall.product.entity.*;
import com.hjrpc.babyyamall.product.feign.CouponFeignService;
import com.hjrpc.babyyamall.product.feign.SearchFeignService;
import com.hjrpc.babyyamall.product.feign.WareFeignService;
import com.hjrpc.babyyamall.product.service.*;
import com.hjrpc.babyyamall.product.vo.BaseAttrs;
import com.hjrpc.babyyamall.product.vo.Images;
import com.hjrpc.babyyamall.product.vo.Skus;
import com.hjrpc.babyyamall.product.vo.SpuSaveVo;
import com.hjrpc.common.constant.ProductConstant;
import com.hjrpc.common.dto.*;
import com.hjrpc.common.utils.PageUtils;
import com.hjrpc.common.utils.Query;
import com.hjrpc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SpuInfoDescDao spuInfoDescDao;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrDao attrDao;

    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSpuDetails(SpuSaveVo saveVo) {
        //保存SPU信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(saveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);

        //保存SPU描述信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", saveVo.getDecript()));
        spuInfoDescDao.insert(spuInfoDescEntity);

        //保存SPU的图片信息
        spuImagesService.saveImages(spuInfoEntity.getId(), saveVo.getImages());

        //保存基础属性对应的值信息到 pms_product_attr_value
        List<BaseAttrs> baseAttrs = saveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(x -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(x, productAttrValueEntity);
            productAttrValueEntity.setAttrValue(x.getAttrValues());
            AttrEntity attrEntity = attrDao.selectById(x.getAttrId());
            BeanUtils.copyProperties(attrEntity, productAttrValueEntity);
            productAttrValueEntity.setQuickShow(x.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //SPU的积分信息,==>>远程调用coupon系统
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(saveVo.getBounds(), spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        try {
            R r = couponFeignService.saveSpuBounds(spuBoundTo);
            log.info(r.toString());
        } catch (Exception e) {
            log.error("couponFeignService.saveSpuBounds远程调用失败:", e);
        }

        //保存SKU信息
        List<Skus> skus = saveVo.getSkus();
        if (CollectionUtils.isEmpty(skus)) {
            return;
        }
        skus.stream().forEach(skuVo -> {
            //1.保存SKU基础信息
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(skuVo, skuInfoEntity);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());//所属分类id
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());//品牌id
            String defaultImage = "";//默认图片
            for (Images image : skuVo.getImages()) {
                if (image.getDefaultImg() == 1) {//1是默认图片
                    defaultImage = image.getImgUrl();
                }
            }
            skuInfoEntity.setSkuDefaultImg(defaultImage);
            skuInfoEntity.setSaleCount(0L);//销量
            skuInfoService.save(skuInfoEntity);

            //2.保存SKU的图片信息pms_sku_images
            skuImagesService.saveImages(skuInfoEntity.getSkuId(), skuVo.getImages());

            //3.保存SKU的销售属性pms_sku_sale_attr_value
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = skuVo.getAttr().stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            //4.保存SKU的优惠、满减等信息 ==>>远程调用coupon系统
            if (skuVo.getFullCount() > 0 || skuVo.getFullPrice().compareTo(BigDecimal.ZERO) == 1) {
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(skuVo, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                skuReductionTo.setMemberPrice(skuVo.getMemberPrice().stream().map(memberPrice -> {
                    MemberPriceTo memberPriceTo = new MemberPriceTo();
                    BeanUtils.copyProperties(memberPrice, memberPriceTo);
                    return memberPriceTo;
                }).collect(Collectors.toList()));

                try {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    log.info(r.toString());
                } catch (Exception e) {
                    log.error("couponFeignService.saveSkuReduction远程调用失败:", e);
                }
            }
        });
    }

    @Override
    public PageUtils queryPageWithCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(x -> x.eq("id", key).or().like("spu_name", key));
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && Long.parseLong(catelogId) != 0) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && Long.parseLong(brandId) != 0) {
            queryWrapper.eq("brand_id", brandId);
        }

        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status) && Integer.parseInt(status) != 0) {
            queryWrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        //根据spuId查询所有的sku信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        //根据spuId获取所有快速展示的属性集合
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>()
                .eq("spu_id", spuId));
        //收集所有的属性ID
        Set<Long> attrIds = new HashSet<>();
        productAttrValueEntities.forEach(x -> attrIds.add(x.getAttrId()));

        //根据属性ID查询所有满足快速查询的属性ID
        Set<Long> fastSearchTypeAttrIds = attrDao.selectFastSearchTypeAttrIds(attrIds);

        //过滤出所有快速显示的属性
        List<Attr4SearchTo> attrs = productAttrValueEntities.stream()
                .filter(x -> fastSearchTypeAttrIds.contains(x.getAttrId()))
                .map(x -> {
                    Attr4SearchTo attr4SearchTo = new Attr4SearchTo();
                    BeanUtils.copyProperties(x, attr4SearchTo);
                    return attr4SearchTo;
                })
                .collect(Collectors.toList());

        //将sku对象封装成es使用的sku对象信息， 填充了是否有库存、品牌信息
        List<Sku4SearchTo> sku4SearchTos = skuInfoEntities.stream().map(skuInfoEntity -> {
            Sku4SearchTo sku4SearchTo = new Sku4SearchTo();
            BeanUtils.copyProperties(skuInfoEntity, sku4SearchTo);
            sku4SearchTo.setSkuPrice(skuInfoEntity.getPrice());
            sku4SearchTo.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            //调用库存系统
            Boolean hasStock = null;
            try {
                hasStock = wareFeignService.hasStock(skuInfoEntity.getSkuId());
            } catch (Exception e) {
                log.error("远程调用仓库系出现异常{}",e);
            }
            sku4SearchTo.setHasStock(hasStock);
            sku4SearchTo.setHotScore(0L);

            //读取品牌信息
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            sku4SearchTo.setBrandImg(brandEntity.getLogo());
            sku4SearchTo.setBrandName(brandEntity.getName());

            //读取分类信息
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            sku4SearchTo.setCatalogName(categoryEntity.getName());

            //填充所有属性信息
            sku4SearchTo.setAttrs(attrs);
            return sku4SearchTo;
        }).collect(Collectors.toList());

        //将商品信息sku4SearchTos推送到search服务
        searchFeignService.up(sku4SearchTos);

        // 修改SPU状态为已上架
        update(new UpdateWrapper<SpuInfoEntity>().set("publish_status",
                ProductConstant.PublishStatusEnum.ASSIGNED.getCode())
                .eq("id", spuId));
    }
}